<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    

    <meta name="baidu-site-verification" content="lt822VnP06" />
    <meta name="baidu-site-verification" content="0Ajixw1Puk" />
    <meta name="google-site-verification" content="gCQD0Y6f0YlPTZTAjp_mqms4C7TlkMWrg3Xy0mFdMwI" />
    <title>spring结合rabbitmq---简单的demo | Giraffe&#39;s Home</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="在做搜索服务时，当业务方数据源改变时，需要改变搜索引擎中索引的数据。可以定时拉取也可以实时推送。为了实现同步更新，选择了实时推送。实时推送也有两种方式，一种是提供索引更新接口供业务方调用，在接口中将变化的数据更新到搜索引擎中；另一种是使用消息队列，业务方在数据改变时，将改变的数据插入队列，服务端的消费者实时监听队列，并进行索引更新。考虑到使用消息队列有三点好处，选择了第二种方式。使用消息队列的好">
<meta property="og:type" content="article">
<meta property="og:title" content="spring结合rabbitmq---简单的demo">
<meta property="og:url" content="http://yemengying.com/2015/09/19/spring-rabbitmq-demo/index.html">
<meta property="og:site_name" content="Giraffe's Home">
<meta property="og:description" content="在做搜索服务时，当业务方数据源改变时，需要改变搜索引擎中索引的数据。可以定时拉取也可以实时推送。为了实现同步更新，选择了实时推送。实时推送也有两种方式，一种是提供索引更新接口供业务方调用，在接口中将变化的数据更新到搜索引擎中；另一种是使用消息队列，业务方在数据改变时，将改变的数据插入队列，服务端的消费者实时监听队列，并进行索引更新。考虑到使用消息队列有三点好处，选择了第二种方式。使用消息队列的好">
<meta property="og:image" content="https://pic.yupoo.com/jiananshi/3ffdf388/a89e7188.jpg">
<meta property="og:updated_time" content="2018-12-14T09:25:27.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="spring结合rabbitmq---简单的demo">
<meta name="twitter:description" content="在做搜索服务时，当业务方数据源改变时，需要改变搜索引擎中索引的数据。可以定时拉取也可以实时推送。为了实现同步更新，选择了实时推送。实时推送也有两种方式，一种是提供索引更新接口供业务方调用，在接口中将变化的数据更新到搜索引擎中；另一种是使用消息队列，业务方在数据改变时，将改变的数据插入队列，服务端的消费者实时监听队列，并进行索引更新。考虑到使用消息队列有三点好处，选择了第二种方式。使用消息队列的好">
<meta name="twitter:image" content="https://pic.yupoo.com/jiananshi/3ffdf388/a89e7188.jpg">
    

    

    
        <link rel="icon" href="https://yemengying.com/qiniu/image/image/favicon.png" />
    


    <link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/lib/open-sans/styles.css">
    <link rel="stylesheet" href="/lib/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/lib/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/lib/fancybox/jquery.fancybox.css">
    
    
        <script type="text/javascript">
(function(i,s,o,g,r,a,m) {i['GoogleAnalyticsObject']=r;i[r]=i[r]||function() {
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-75861791-1', 'auto');
ga('send', 'pageview');

</script>
    
    
    
        <script>
var _hmt = _hmt || [];
(function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?44bb8bfb1a576270255713e37746eb82";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();
</script>

    

</head>
<body>
    <script src="//github.elemecdn.com/jiananshi/req/0.1.0/lib/req.js"></script>
    <script src="//npm.elemecdn.com/jinkela@1.2.18/umd.js"></script>
    <script src="//github.elemecdn.com/jiananshi/DisqusJS/2.0.8/index.js"></script>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">Giraffe&#39;s Home</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">归档</a>
                
                    <a class="main-nav-link" href="/categories">分类</a>
                
                    <a class="main-nav-link" href="/tags">标签</a>
                
                    <a class="main-nav-link" href="/about">关于</a>
                
                    <a class="main-nav-link" href="/message">留言</a>
                
                    <a class="main-nav-link" href="/friends">友链</a>
                
                    <a class="main-nav-link" href="/reading">正在读...</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="https://pic.yupoo.com/jiananshi/e85e4303/735cf286.jpeg" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td><a class="main-nav-link" href="/.">首页</a></td>
                
                    <td><a class="main-nav-link" href="/archives">归档</a></td>
                
                    <td><a class="main-nav-link" href="/categories">分类</a></td>
                
                    <td><a class="main-nav-link" href="/tags">标签</a></td>
                
                    <td><a class="main-nav-link" href="/about">关于</a></td>
                
                    <td><a class="main-nav-link" href="/message">留言</a></td>
                
                    <td><a class="main-nav-link" href="/friends">友链</a></td>
                
                    <td><a class="main-nav-link" href="/reading">正在读...</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="https://pic.yupoo.com/jiananshi/e85e4303/735cf286.jpeg" />
            <h2 id="name">Giraffe</h2>
            <h3 id="title">Java Developer</h3>
            <span id="location"><i class="fa fa-map-marker"></i>Shanghai, China</span>
            <a id="follow" target="_blank" href="https://github.com/giraffe0813/">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                56
                <span>文章</span>
            </div>
            <div class="article-info-block">
                36
                <span>标签</span>
            </div>
        </div>
        <div class="profile-block recent-comments">
            <p class="recent-comments-title">最新评论</p>
            <ul id="disqus-recent-comments" class="recent-comments-container">
            </ul>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/giraffe0813" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/atom.xml" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="2015/09/19/spring-rabbitmq-demo/" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            spring结合rabbitmq---简单的demo
        </h1>
    

                <div class="article-meta">
                    
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/2015/09/19/spring-rabbitmq-demo/">
            <time datetime="2015-09-19T06:55:43.000Z" itemprop="datePublished">2015-09-19</time>
        </a>
    </div>


                    
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/spring/">spring</a>
    </div>

                    
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/java/">java</a>, <a class="tag-link" href="/tags/rabbitMq/">rabbitMq</a>, <a class="tag-link" href="/tags/spring/">spring</a>
    </div>

                </div>
            </header>
        
        <div class="article-entry" itemprop="articleBody">
        
            
                <div id="toc" class="toc-article">
                <strong class="toc-title">文章目录</strong>
                    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#本地安装rabbitmq"><span class="toc-number">1.</span> <span class="toc-text">本地安装rabbitmq</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#安装brew"><span class="toc-number">1.1.</span> <span class="toc-text">安装brew</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#利用brew安装rabbitmq"><span class="toc-number">1.2.</span> <span class="toc-text">利用brew安装rabbitmq</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#实现demo"><span class="toc-number">2.</span> <span class="toc-text">实现demo</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#添加maven依赖"><span class="toc-number">2.1.</span> <span class="toc-text">添加maven依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#添加配置文件"><span class="toc-number">2.2.</span> <span class="toc-text">添加配置文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#生产者开发（插入消息）"><span class="toc-number">2.3.</span> <span class="toc-text">生产者开发（插入消息）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#消费者开发"><span class="toc-number">2.4.</span> <span class="toc-text">消费者开发</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#git-地址："><span class="toc-number">3.</span> <span class="toc-text">git 地址：</span></a></li></ol>
                </div>
            
            <blockquote>
<p>在做搜索服务时，当业务方数据源改变时，需要改变搜索引擎中索引的数据。可以<code>定时拉取</code>也可以<code>实时推送</code>。为了实现同步更新，选择了实时推送。实时推送也有两种方式，一种是提供索引更新接口供业务方调用，在接口中将变化的数据更新到搜索引擎中；另一种是使用消息队列，业务方在数据改变时，将改变的数据插入队列，服务端的消费者实时监听队列，并进行索引更新。考虑到使用消息队列有三点好处，选择了第二种方式。<code>使用消息队列的好处</code>: 一，使用消息队列可以异步处理更新操作降低接口响应时间；二，对于消费端由于不可预测原因导致消息无法处理时，数据可以暂存在队列中，等消费者服务恢复后可以继续处理历史数据,提高可用性；三，将业务方的服务和索引更新服务解耦。下面简单记录一下一个简单的spring+rabbitmq的demo实现，只实现了简单的消息生产和消费。</p>
</blockquote>
<p>参考了下面几篇博客：<br><a href="http://syntx.io/getting-started-with-rabbitmq-using-the-spring-framework/" target="_blank" rel="external">http://syntx.io/getting-started-with-rabbitmq-using-the-spring-framework/</a><br><a href="https://blog.codecentric.de/en/2011/04/amqp-messaging-with-rabbitmq/" target="_blank" rel="external">https://blog.codecentric.de/en/2011/04/amqp-messaging-with-rabbitmq/</a><br><a href="http://wb284551926.iteye.com/blog/2212869" target="_blank" rel="external">http://wb284551926.iteye.com/blog/2212869</a></p>
<a id="more"></a>
<h2 id="本地安装rabbitmq"><a href="#本地安装rabbitmq" class="headerlink" title="本地安装rabbitmq"></a>本地安装rabbitmq</h2><p>只介绍mac系统下如何安装</p>
<h3 id="安装brew"><a href="#安装brew" class="headerlink" title="安装brew"></a>安装brew</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">ruby -e &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)&quot;</div></pre></td></tr></table></figure>
<h3 id="利用brew安装rabbitmq"><a href="#利用brew安装rabbitmq" class="headerlink" title="利用brew安装rabbitmq"></a>利用brew安装rabbitmq</h3><p>1.输入命令</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">brew install rabbitmq</div></pre></td></tr></table></figure>
<p>2.添加配置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">export PATH=$PATH:$(brew --prefix)/sbin</div></pre></td></tr></table></figure>
<p>3.可以禁用用不着的插件</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">rabbitmq-plugins disable --offline rabbitmq_stomp</div><div class="line">rabbitmq-plugins disable --offline rabbitmq_mqtt</div></pre></td></tr></table></figure>
<p>4.启动rabbitmq server 直接输入下面的命令</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">rabbitmq-server</div></pre></td></tr></table></figure>
<p>5.如果打印出下面的东东就是启动成功了，默认端口是5672</p>
<p><img src="https://pic.yupoo.com/jiananshi/3ffdf388/a89e7188.jpg" alt="spring-rabbitMq"></p>
<h2 id="实现demo"><a href="#实现demo" class="headerlink" title="实现demo"></a>实现demo</h2><p>首先要有个可以运行的spring + maven的项目</p>
<h3 id="添加maven依赖"><a href="#添加maven依赖" class="headerlink" title="添加maven依赖"></a>添加maven依赖</h3><p>在pom文件中添加rabbitmq相关的依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.rabbitmq<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>amqp-client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">version</span>&gt;</span>3.5.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.amqp<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-rabbit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">version</span>&gt;</span>1.5.0.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure>
<h3 id="添加配置文件"><a href="#添加配置文件" class="headerlink" title="添加配置文件"></a>添加配置文件</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</div><div class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></div><div class="line">	<span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span> <span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span></div><div class="line">	<span class="attr">xmlns:rabbit</span>=<span class="string">"http://www.springframework.org/schema/rabbit"</span> <span class="attr">xmlns:p</span>=<span class="string">"http://www.springframework.org/schema/p"</span></div><div class="line">	<span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></div><div class="line">http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd"&gt;</div><div class="line"></div><div class="line">	<span class="comment">&lt;!-- 扫描包 --&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">context:component-scan</span> <span class="attr">base-package</span>=<span class="string">"ymy.com.rabbitmq.demo.service.impl.*"</span> /&gt;</span></div><div class="line"></div><div class="line">	<span class="tag">&lt;<span class="name">context:annotation-config</span> /&gt;</span></div><div class="line"></div><div class="line">	<span class="comment">&lt;!-- 连接本地rabbitmq --&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">rabbit:connection-factory</span> <span class="attr">id</span>=<span class="string">"connectionFactory"</span></span></div><div class="line">		<span class="attr">host</span>=<span class="string">"localhost"</span> <span class="attr">port</span>=<span class="string">"5672"</span> /&gt;</div><div class="line"></div><div class="line">	<span class="tag">&lt;<span class="name">rabbit:admin</span> <span class="attr">connection-factory</span>=<span class="string">"connectionFactory"</span> <span class="attr">id</span>=<span class="string">"amqpAdmin"</span> /&gt;</span></div><div class="line"></div><div class="line">	<span class="comment">&lt;!-- queue 队列声明 --&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">rabbit:queue</span> <span class="attr">id</span>=<span class="string">"rabbit_queue_one"</span> <span class="attr">durable</span>=<span class="string">"true"</span></span></div><div class="line">		<span class="attr">auto-delete</span>=<span class="string">"false"</span> <span class="attr">exclusive</span>=<span class="string">"false"</span> <span class="attr">name</span>=<span class="string">"rabbit_queue_one"</span> /&gt;</div><div class="line"></div><div class="line">	<span class="comment">&lt;!-- exchange queue binging key 绑定 --&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">rabbit:direct-exchange</span> <span class="attr">name</span>=<span class="string">"mq-exchange"</span></span></div><div class="line">		<span class="attr">durable</span>=<span class="string">"true"</span> <span class="attr">auto-delete</span>=<span class="string">"false"</span> <span class="attr">id</span>=<span class="string">"mq-exchange"</span>&gt;</div><div class="line">		<span class="tag">&lt;<span class="name">rabbit:bindings</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">rabbit:binding</span> <span class="attr">queue</span>=<span class="string">"rabbit_queue_one"</span> <span class="attr">key</span>=<span class="string">"rabbit_queue_one"</span> /&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">rabbit:bindings</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">rabbit:direct-exchange</span>&gt;</span></div><div class="line"></div><div class="line">	<span class="comment">&lt;!-- spring template声明 --&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">rabbit:template</span> <span class="attr">exchange</span>=<span class="string">"mq-exchange"</span> <span class="attr">id</span>=<span class="string">"amqpTemplate"</span></span></div><div class="line">		<span class="attr">connection-factory</span>=<span class="string">"connectionFactory"</span> /&gt;</div><div class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></div></pre></td></tr></table></figure>
<h3 id="生产者开发（插入消息）"><a href="#生产者开发（插入消息）" class="headerlink" title="生产者开发（插入消息）"></a>生产者开发（插入消息）</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> ymy.com.rabbitmq.demo.service.impl;</div><div class="line"></div><div class="line"><span class="keyword">import</span> org.springframework.amqp.core.AmqpAdmin;</div><div class="line"><span class="keyword">import</span> org.springframework.amqp.core.AmqpTemplate;</div><div class="line"><span class="keyword">import</span> org.springframework.amqp.core.Message;</div><div class="line"><span class="keyword">import</span> org.springframework.amqp.rabbit.connection.ConnectionFactory;</div><div class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</div><div class="line"><span class="keyword">import</span> org.springframework.stereotype.Service;</div><div class="line"></div><div class="line"></div><div class="line"><span class="meta">@Service</span>(<span class="string">"messageProductorService"</span>)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MessageProductorService</span> </span>&#123;</div><div class="line"></div><div class="line">	<span class="meta">@Autowired</span></div><div class="line">	<span class="keyword">private</span> AmqpAdmin admin;</div><div class="line">	<span class="meta">@Autowired</span></div><div class="line">	<span class="keyword">private</span> AmqpTemplate amqpTemplate;</div><div class="line">	<span class="meta">@Autowired</span></div><div class="line">	<span class="keyword">private</span> ConnectionFactory connectionFactory;</div><div class="line"></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pushToMessageQueue</span><span class="params">(String routingKey, String message)</span> </span>&#123;</div><div class="line">		amqpTemplate.convertAndSend(routingKey, message);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="消费者开发"><a href="#消费者开发" class="headerlink" title="消费者开发"></a>消费者开发</h3><p>有两种方式从消息队列中获取消息，一种是自己调用receive方法获得，一种是为队列配置监听类，每当监听的队列中有消息产生，就会被监听的类去除。<br>第一种方式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> ymy.com.rabbitmq.demo.service.impl;</div><div class="line"><span class="keyword">import</span> org.springframework.amqp.core.AmqpTemplate;</div><div class="line"><span class="keyword">import</span> org.springframework.amqp.core.Message;</div><div class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</div><div class="line"><span class="keyword">import</span> org.springframework.stereotype.Service;</div><div class="line"><span class="meta">@Service</span>(<span class="string">"messageConsumerService"</span>)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MessageConsumerService</span> </span>&#123;</div><div class="line">	<span class="meta">@Autowired</span></div><div class="line">	<span class="keyword">private</span> AmqpTemplate amqpTemplate;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">popMessage</span><span class="params">(String destinationQueueName)</span> </span>&#123;</div><div class="line">		Message message = amqpTemplate.receive(destinationQueueName);</div><div class="line">		System.out.println(<span class="keyword">new</span> String(message.getBody()));</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>junit test</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testMessageQueueManager</span><span class="params">()</span></span>&#123;</div><div class="line">       messageProductor.pushToMessageQueue(<span class="string">"rabbit_queue_one"</span>, <span class="string">"hello giraffe"</span>);</div><div class="line">       messageConsumer.popMessage(<span class="string">"rabbit_queue_one"</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>第二种方式<br>配置中添加监听</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- queue litener  观察 监听模式 当有消息到达时会通知监听在对应的队列上的监听对象 taskExecutor这个需要自己实现一个连接池 按照官方说法 除非特别大的数据量 一般不需要连接池--&gt;</span></div><div class="line">   <span class="tag">&lt;<span class="name">rabbit:listener-container</span> <span class="attr">connection-factory</span>=<span class="string">"connectionFactory"</span> <span class="attr">acknowledge</span>=<span class="string">"auto"</span> &gt;</span></div><div class="line">       <span class="tag">&lt;<span class="name">rabbit:listener</span> <span class="attr">queues</span>=<span class="string">"rabbit_queue_one"</span> <span class="attr">ref</span>=<span class="string">"messageConsumerService"</span>/&gt;</span></div><div class="line">   <span class="tag">&lt;/<span class="name">rabbit:listener-container</span>&gt;</span></div></pre></td></tr></table></figure>
<p>消费者类需要实现MessageListener 并实现onMessage方法，当监听的队列中有消息进入时，onMessage方法会被调用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> ymy.com.rabbitmq.demo.service.impl;</div><div class="line"></div><div class="line"><span class="keyword">import</span> org.springframework.amqp.core.Message;</div><div class="line"><span class="keyword">import</span> org.springframework.stereotype.Service;</div><div class="line"><span class="keyword">import</span> org.springframework.amqp.core.MessageListener;</div><div class="line"></div><div class="line"><span class="meta">@Service</span>(<span class="string">"messageConsumerService"</span>)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MessageConsumerService</span> <span class="keyword">implements</span> <span class="title">MessageListener</span></span>&#123;</div><div class="line"></div><div class="line">	<span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onMessage</span><span class="params">(Message message)</span> </span>&#123;</div><div class="line">		System.out.println(<span class="string">"成功取出消息"</span> + <span class="keyword">new</span> String(message.getBody()));</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="git-地址："><a href="#git-地址：" class="headerlink" title="git 地址："></a>git 地址：</h2><div id="badge-container-giraffe0813-spring-rabbit-demo-617348a" class="hexo-github" style="width: 100%"></div>
<script src="/hexo-github/badge.js"></script>
<script type="text/javascript">
  loadStyle("/hexo-github/style.css");
  loadStyle("/hexo-github/octicons/octicons.css");
  new Badge("#badge-container-giraffe0813-spring-rabbit-demo-617348a", "giraffe0813", "spring-rabbit-demo", "617348a", false);
</script>


        
        </div>
        <footer class="article-footer">
            <div class="share-container">



</div>

    <a data-url="http://yemengying.com/2015/09/19/spring-rabbitmq-demo/" data-id="cjtvbucjd003uz15se436lu8s" class="article-share-link"><i class="fa fa-share"></i>分享到</a>
<script>
    (function ($) {
        // Prevent duplicate binding
        if (typeof(__SHARE_BUTTON_BINDED__) === 'undefined' || !__SHARE_BUTTON_BINDED__) {
            __SHARE_BUTTON_BINDED__ = true;
        } else {
            return;
        }
        $('body').on('click', function() {
            $('.article-share-box.on').removeClass('on');
        }).on('click', '.article-share-link', function(e) {
            e.stopPropagation();

            var $this = $(this),
                url = $this.attr('data-url'),
                encodedUrl = encodeURIComponent(url),
                id = 'article-share-box-' + $this.attr('data-id'),
                offset = $this.offset(),
                box;

            if ($('#' + id).length) {
                box = $('#' + id);

                if (box.hasClass('on')){
                    box.removeClass('on');
                    return;
                }
            } else {
                var html = [
                    '<div id="' + id + '" class="article-share-box">',
                        '<input class="article-share-input" value="' + url + '">',
                        '<div class="article-share-links">',
                            '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="fa fa-twitter article-share-twitter" target="_blank" title="Twitter"></a>',
                            '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="fa fa-facebook article-share-facebook" target="_blank" title="Facebook"></a>',
                            '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="fa fa-pinterest article-share-pinterest" target="_blank" title="Pinterest"></a>',
                            '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="fa fa-google article-share-google" target="_blank" title="Google+"></a>',
                        '</div>',
                    '</div>'
                ].join('');

              box = $(html);

              $('body').append(box);
            }

            $('.article-share-box.on').hide();

            box.css({
                top: offset.top + 25,
                left: offset.left
            }).addClass('on');

        }).on('click', '.article-share-box', function (e) {
            e.stopPropagation();
        }).on('click', '.article-share-box-input', function () {
            $(this).select();
        }).on('click', '.article-share-box-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
        });
    })(jQuery);
</script>

            
    
        <a href="http://yemengying.com/2015/09/19/spring-rabbitmq-demo/#comments" class="article-comment-link disqus-comment-count" data-disqus-url="http://yemengying.com/2015/09/19/spring-rabbitmq-demo/">评论</a>
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/2015/09/26/cleancode-builder/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    使代码更简洁(三)---利用Builder Pattern为对象属性赋值
                
            </div>
        </a>
    
    
        <a href="/2015/09/12/spring-transaction/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">spring事务管理总结</div>
        </a>
    
</nav>


    
    <script>
   DisqusJS.getArticleComments();
   </script>
</article>


    
    <section id="comments">
    
        
    <div id="disqus_thread">
        <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    </div>

    
    </section>

</section>
            
        </div>
        <footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            &copy; 2019 Mengying Ye<br>
            Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
        </div>
    </div>
</footer>
        
    
   <script>
   DisqusJS.getRecentComments(document.querySelector('#disqus-recent-comments'));
   </script>



    
        <script src="/lib/fancybox/jquery.fancybox.pack.js"></script>
    


<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>
